import React, { useState, useEffect } from "react";
import { useNavigate } from "react-router-dom";
import { ImageUploader, Space, Toast, Dialog } from "antd-mobile";
import { LockOutline, UserOutline, PhoneFill } from "antd-mobile-icons";
import "./Zhu.css";
import axios from "./axios";

export default function Register() {
  const [fileList, setFileList] = useState([]);
  const navigate = useNavigate();
  const [formData, setFormData] = useState({
    username: "",
    phone: "",
    password: "",
    confirmPassword: "",
  });
  const [errors, setErrors] = useState({});
  const [isSubmitting, setIsSubmitting] = useState(false);

  useEffect(() => {
    console.log(fileList);
  }, [fileList]);

  const uploadImage = async (file) => {
    try {
      const formData = new FormData();
      formData.append("file", file);

      const response = await axios.post(
        "http://127.0.0.1:3000/upload",
        formData,
        {
          headers: {
            "Content-Type": "multipart/form-data",
          },
        }
      );

      return {
        url: response.data.url,
      };
    } catch (error) {
      Toast.show({
        content: "上传失败",
        icon: "fail",
      });
      throw error;
    }
  };

  const handleFileListChange = (newFileList) => {
    setFileList(newFileList);
  };

  const handleChange = (e) => {
    const { name, value } = e.target;
    setFormData({
      ...formData,
      [name]: value,
    });

    if (errors[name]) {
      setErrors({
        ...errors,
        [name]: null,
      });
    }
  };

  const validate = () => {
    const newErrors = {};
    if (!formData.username.trim()) newErrors.username = "请输入用户名";
    if (!formData.phone.trim()) newErrors.phone = "请输入手机号";
    if (!/^1[3-9]\d{9}$/.test(formData.phone)) newErrors.phone = "请输入正确的手机号";
    if (!formData.password) newErrors.password = "请输入密码";
    if (formData.password.length < 6) newErrors.password = "密码至少6位";
    if (!formData.confirmPassword) newErrors.confirmPassword = "请确认密码";
    if (formData.password !== formData.confirmPassword) {
      newErrors.confirmPassword = "两次输入的密码不一致";
    }
    return newErrors;
  };

  const handleSubmit = (e) => {
    e.preventDefault();
    const validationErrors = validate();
    if (Object.keys(validationErrors).length > 0) {
      setErrors(validationErrors);
      return;
    }

    setIsSubmitting(true);
    axios
      .post("/zhu", {
        username: formData.username,
        phone: formData.phone,
        password: formData.password,
        image: fileList[0]?.url,
      })
      .then((res) => {
        console.log(res.data);
        if (res.data.code === 200) {
          Toast.show({
            content: "注册成功",
            icon: "success",
            afterClose: () => navigate("/login"),
          });
        } else {
          Toast.show({
            content: res.data.msg || "注册失败",
            icon: "fail",
          });
        }
      })
      .catch((error) => {
        console.error("注册失败:", error);
        Toast.show({
          content: error.response?.data?.message || "注册失败，请稍后再试",
          icon: "fail",
        });
      })
      .finally(() => {
        setIsSubmitting(false);
      });
  };

  return (
    <div className="register-container">
      <div className="register-card">
        <h1 className="register-title">创建账号</h1>
        <p className="register-subtitle">加入我们，开启全新体验</p>

        <div className="avatar-uploader">
          <ImageUploader
            value={fileList}
            onChange={handleFileListChange}
            upload={uploadImage}
            maxCount={1}
            style={{ "--cell-size": "100px" }}
            onDelete={() =>
              Dialog.confirm({
                content: "确定删除头像吗？",
                onConfirm: async () => {
                  return true;
                },
              })
            }
          />
          <div className="uploader-label">点击上传头像</div>
        </div>

        <form onSubmit={handleSubmit} className="register-form">
          <div className={`form-group ${errors.username ? "has-error" : ""}`}>
            <div className="input-wrapper">
              <UserOutline className="input-icon" />
              <input
                type="text"
                name="username"
                value={formData.username}
                onChange={handleChange}
                placeholder="请输入用户名"
                autoComplete="username"
              />
            </div>
            {errors.username && (
              <div className="error-message">{errors.username}</div>
            )}
          </div>

          <div className={`form-group ${errors.phone ? "has-error" : ""}`}>
            <div className="input-wrapper">
              <PhoneFill className="input-icon" />
              <input
                type="text"
                name="phone"
                value={formData.phone}
                onChange={handleChange}
                placeholder="请输入手机号"
                autoComplete="phone"
                maxLength="11"
              />
            </div>
            {errors.phone && (
              <div className="error-message">{errors.phone}</div>
            )}
          </div>

          <div className={`form-group ${errors.password ? "has-error" : ""}`}>
            <div className="input-wrapper">
              <LockOutline className="input-icon" />
              <input
                type="password"
                name="password"
                value={formData.password}
                onChange={handleChange}
                placeholder="请输入密码 (至少6位)"
                autoComplete="new-password"
              />
            </div>
            {errors.password && (
              <div className="error-message">{errors.password}</div>
            )}
          </div>

          <div className={`form-group ${errors.confirmPassword ? "has-error" : ""}`}>
            <div className="input-wrapper">
              <LockOutline className="input-icon" />
              <input
                type="password"
                name="confirmPassword"
                value={formData.confirmPassword}
                onChange={handleChange}
                placeholder="请再次输入密码"
                autoComplete="new-password"
              />
            </div>
            {errors.confirmPassword && (
              <div className="error-message">{errors.confirmPassword}</div>
            )}
          </div>

          <button
            type="submit"
            className="register-button"
            disabled={isSubmitting}
          >
            {isSubmitting ? (
              <span className="loading-text">注册中...</span>
            ) : (
              "立即注册"
            )}
          </button>

          <div className="login-link">
            已有账号? <span onClick={() => navigate("/login")}>立即登录</span>
          </div>
        </form>
      </div>
    </div>
  );
}